package team

import (
	"data/config"
	"data/view"
	"data/view/auth"
	"data/view/auth/auth_const"
	"data/view/common"
	"data/view/other"
	"data/view/user"
	"fmt"
	"public/message"
	"public/mysqldb"
	"public/tools"
	"time"

	"github.com/ant0ine/go-json-rest/rest"
)

/*
	新增团队
*/
func Add(w rest.ResponseWriter, r *rest.Request) {
	var req AddParam
	tools.GetRequestJsonObj(r, &req)

	//参数检测
	if !tools.CheckParam(req.Access_token, req.Name) || len(req.Leader) == 0 || len(req.Region_info) == 0 {
		w.WriteJson(message.GetErrorMsg(message.ParameterInvalid, req))
		return
	}
	//验证token，并获取用户名
	username, _, bfind := user.GetUserFromToken(req.Access_token)
	if !bfind {
		w.WriteJson(message.GetErrorMsg(message.TokenFailure))
		return
	}
	u, bb := user.GetUserDetail(username)
	if !bb {
		w.WriteJson(message.GetErrorMsg(message.UserNotExisted))
		return
	}
	//权限检验
	b := auth.CheckRoleAuth(u.Business_role, auth_const.M_9, auth_const.L_A, auth_const.L_C)
	if !b {
		w.WriteJson(message.GetErrorMsg(message.UserMenuNotExisted))
		return
	}
	for _, v := range req.Region_info {
		tmp := other.OnGetRegion(v.Province, v.City, v.Region)
		if tmp.Id == 0 {
			w.WriteJson(message.GetErrorMsg(message.ParameterInvalid, "省市区不存在"))
			return
		}
		if !CheckRegionIsRight(v.Province, v.City, v.Region) {
			w.WriteJson(message.GetErrorMsg(message.ParameterInvalid, "省市区有误"))
			return
		}
	}

	var db mysqldb.MySqlDB
	defer db.OnDestoryDB()
	orm := db.OnGetDBOrm(config.GetDbUrl())

	var team view.Team_info_tbl
	team.Name = req.Name
	team.Leader = fmt.Sprintf("%s", req.Leader[0])
	for i := 1; i < len(req.Leader); i++ {
		team.Leader += common.SPLIT + fmt.Sprintf("%s", req.Leader[i])
	}
	team.Is_vaild = 1
	team.Create_time = time.Now()

	if orm.Create(&team).Error != nil {
		w.WriteJson(message.GetErrorMsg(message.ExistedError))
		return
	}
	orm.Last(&team) //获取自增主键
	user.OnDeleteUserCache("")
	mess := OnAddTeamRegionAndMember(req.Name, req.Member, team.Id, req.Region_info)
	w.WriteJson(mess)

}

/*
	编辑删除团队
*/
func DoAction(w rest.ResponseWriter, r *rest.Request) {
	var req AddParam
	tools.GetRequestJsonObj(r, &req)

	//参数检测
	if !tools.CheckParam(req.Access_token, req.Name) || req.Action == 0 {
		w.WriteJson(message.GetErrorMsg(message.ParameterInvalid, req))
		return
	}
	//验证token，并获取用户名
	username, _, bfind := user.GetUserFromToken(req.Access_token)
	if !bfind {
		w.WriteJson(message.GetErrorMsg(message.TokenFailure))
		return
	}
	u, bb := user.GetUserDetail(username)
	if !bb {
		w.WriteJson(message.GetErrorMsg(message.UserNotExisted))
		return
	}
	var db mysqldb.MySqlDB
	defer db.OnDestoryDB()
	orm := db.OnGetDBOrm(config.GetDbUrl())

	var team view.Team_info_tbl
	orm.Where("name = ? ", req.Name).Find(&team)
	if team.Id == 0 {
		w.WriteJson(message.GetErrorMsg(message.NotFindError))
		return
	}
	if len(req.Region_info) > 0 {
		for _, v := range req.Region_info {
			tmp := other.OnGetRegion(v.Province, v.City, v.Region)
			if tmp.Id == 0 {
				w.WriteJson(message.GetErrorMsg(message.ParameterInvalid, "省市区不存在"))
				return
			}
			if !CheckRegionIsRight(v.Province, v.City, v.Region) {
				w.WriteJson(message.GetErrorMsg(message.ParameterInvalid, "省市区有误"))
				return
			}
		}
	}
	var err error
	if req.Action == 1 { //编辑
		//权限检验
		b := auth.CheckRoleAuth(u.Business_role, auth_const.M_9, auth_const.L_A, auth_const.L_C)
		if !b {
			w.WriteJson(message.GetErrorMsg(message.UserMenuNotExisted))
			return
		}
		var t view.Team_info_tbl
		t.Name = req.Name_new
		if len(req.Leader) > 0 {
			t.Leader = fmt.Sprintf("%s", req.Leader[0])
			for i := 1; i < len(req.Leader); i++ {
				team.Leader += common.SPLIT + fmt.Sprintf("%s", req.Leader[i])
			}
		}
		t.Is_vaild = req.Is_vaild
		err = orm.Table("team_info_tbl").Where("name = ? ", req.Name).Updates(t).Error

		if err != nil {
			w.WriteJson(message.GetErrorMsg(message.ExistedError))
			return
		}
		if len(req.Name_new) > 0 {
			req.Name = req.Name_new
		}
		mess := OnUpdateTeamRegionAndMember(req.Name, req.Member, team.Id, req.Region_info)
		w.WriteJson(mess)

	} else if req.Action == 2 { //删除
		//权限检验
		b := auth.CheckRoleAuth(u.Business_role, auth_const.M_9, auth_const.L_C)
		if !b {
			w.WriteJson(message.GetErrorMsg(message.UserMenuNotExisted))
			return
		}
		//判断能否删除
		if !CheckTeamIsDelete(team.Id) {
			w.WriteJson(message.GetErrorMsg(message.InValidOp, "存在成员，无法删除"))
			return
		}
		err = orm.Table("team_info_tbl").Where("name = ? ", req.Name).Delete(&view.Team_info_tbl{}).Error
		if err != nil {
			w.WriteJson(message.GetErrorMsg(message.UnknownError))
			return
		}
		w.WriteJson(message.GetSuccessMsg())
	} else {
		w.WriteJson(message.GetErrorMsg(message.ParameterInvalid))
		return
	}
	user.OnDeleteUserCache("")
}

/*
	获取全部团队详情
*/
func GetAllDetail(w rest.ResponseWriter, r *rest.Request) {
	var req AddParam
	tools.GetRequestJsonObj(r, &req)

	//参数检测
	if !tools.CheckParam(req.Access_token) {
		w.WriteJson(message.GetErrorMsg(message.ParameterInvalid, req))
		return
	}
	//验证token，并获取用户名
	username, _, bfind := user.GetUserFromToken(req.Access_token)
	if !bfind {
		w.WriteJson(message.GetErrorMsg(message.TokenFailure))
		return
	}
	us, bb := user.GetUserDetail(username)
	if !bb {
		w.WriteJson(message.GetErrorMsg(message.UserNotExisted))
		return
	}
	//权限检验
	b := auth.CheckRoleAuth(us.Business_role, auth_const.M_9, auth_const.L_A, auth_const.L_B, auth_const.L_C)
	if !b {
		w.WriteJson(message.GetErrorMsg(message.UserMenuNotExisted))
		return
	}
	var result []TeamInfoDetail
	mp := GetTeamDetail("")
	if len(mp) > 0 {
		for _, v := range mp {
			result = append(result, v)
		}
	}
	msg := message.GetSuccessMsg(message.NormalMessageId)
	msg.Data = result
	w.WriteJson(msg)

}
